package com.oasis.oasislib.utils;

import android.Manifest;
import android.content.Context;
import android.content.pm.PackageManager;
import android.os.Build;
import android.support.v4.app.ActivityCompat;
import android.view.WindowManager;

import com.blankj.utilcode.util.PhoneUtils;
import com.oasis.oasislib.base.HttpCallBack;


import java.io.IOException;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Locale;

public class CommonUtil {



	public static String getUnique(Context context) {
		//这是拒绝imei 权限的情况下 获取的设备唯一码   但是有个缺点  小数量的用户量 可以满足需求 比如鑫恩华的app
		//##360--msm8952--system2--6.0.1--c545f40a
		//这是允许imei 权限的情况下  获取的设备唯一码
		//**918021496067999--##360--msm8952--system2--6.0.1--c545f40a

		//如果数据库中出现了两条数据  * 后面的字符串相同的情况  就是使用了双开软件！！！

		//如果本应用
		String other = "##"+Build.BRAND+"--"+Build.BOARD+"--"+Build.USER+"--"+Build.VERSION.RELEASE+"--"+Build.SERIAL ;
		if (ActivityCompat.checkSelfPermission(context, Manifest.permission.READ_PHONE_STATE) != PackageManager.PERMISSION_GRANTED) {
			//com.blankj.utilcode.util.ToastUtils.showLong("需要 IMEI 权限");
			return other;  //直接return other  是没有获取到权限！！
		}

		String uniqueid = PhoneUtils.getDeviceId() ;

		if(uniqueid==null){//没有获取用户的权限许可！！！ 所以得不到imei
			uniqueid = other;//直接return other  是没有获取到权限！！
			return uniqueid;
		}
		LogUtil.e("getUnique","uniqueid--"+uniqueid);
		return "**"+uniqueid+"--"+other;
	}


	static String webUrl3 = "http://www.taobao.com";

	public static String pattern = "yyyy-MM-dd HH:mm:ss" ;

	public static void getCurrentTimeWithCallback(final HttpCallBack httpCallBack){
		new Thread(new Runnable() {
			@Override
			public void run() {
				try {
					URL url = new URL(webUrl3);// 取得资源对象
					URLConnection uc = url.openConnection();// 生成连接对象
					uc.connect();// 发出连接
					long ld = uc.getDate();// 读取网站日期时间
					Date date = new Date(ld);// 转换为标准时间对象
					SimpleDateFormat sdf = new SimpleDateFormat(pattern, Locale.CHINA);// 输出北京时间
					httpCallBack.onSuccess(sdf.format(date));
				} catch (MalformedURLException e) {
					e.printStackTrace();
					httpCallBack.onError(null,true);
				} catch (IOException e) {
					e.printStackTrace();
					httpCallBack.onError(null,true);
				}

				httpCallBack.onFinished();

			}
		}).start();
	}

	public static Date stringToDate(String source,String pattern) {
		SimpleDateFormat simpleDateFormat= new SimpleDateFormat(pattern);
		Date date = null;
		try {
			date = simpleDateFormat.parse(source);
		} catch (Exception e) {
		}
		return date;
	}

	private static Date getWebsiteDatetime(String webUrl){
		try {
			URL url = new URL(webUrl);// 取得资源对象
			URLConnection uc = url.openConnection();// 生成连接对象
			uc.connect();// 发出连接
			long ld = uc.getDate();// 读取网站日期时间
			Date date = new Date(ld);// 转换为标准时间对象
//			SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss", Locale.CHINA);// 输出北京时间
//			return sdf.format(date);
			return date;
		} catch (MalformedURLException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
		return null;
	}

	public static Date getCurrentTime(){
		return getWebsiteDatetime(webUrl3) ;
	}

	public static String formatTime(Date date){
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss", Locale.CHINA);
		return sdf.format(date);
	}
	
	public static int getScreenHeight(Context context){
		WindowManager wm = (WindowManager) context
                .getSystemService(Context.WINDOW_SERVICE);
		return wm.getDefaultDisplay().getHeight() ;
	}
	
	public static int getScreenWidth(Context context){
		WindowManager wm = (WindowManager) context
                .getSystemService(Context.WINDOW_SERVICE);
		return wm.getDefaultDisplay().getWidth() ;
	}
	
	/**
	 * �õ�unixʱ��
	 * @return  1429761592
	 */
	public static int getUnixTime(){
		long s = System.currentTimeMillis() ;
		return (int) (s/1000) ;
	}
	
	public static String fromEncodedUnicode(char[] in, int off, int len) {
		char aChar;
		char[] out = new char[len]; // 只短不长
		int outLen = 0;
		int end = off + len;
		while (off < end) {

			aChar = in[off++];

			if (aChar == '\\') {

				aChar = in[off++];

				if (aChar == 'u') {

					// Read the xxxx

					int value = 0;

					for (int i = 0; i < 4; i++) {

						aChar = in[off++];

						switch (aChar) {

						case '0':

						case '1':

						case '2':

						case '3':

						case '4':

						case '5':

						case '6':

						case '7':

						case '8':

						case '9':

							value = (value << 4) + aChar - '0';

							break;

						case 'a':

						case 'b':

						case 'c':

						case 'd':

						case 'e':

						case 'f':

							value = (value << 4) + 10 + aChar - 'a';

							break;

						case 'A':

						case 'B':

						case 'C':

						case 'D':

						case 'E':

						case 'F':

							value = (value << 4) + 10 + aChar - 'A';

							break;

						default:

							throw new IllegalArgumentException(
									"Malformed \\uxxxx encoding.");

						}

					}

					out[outLen++] = (char) value;

				} else {

					if (aChar == 't') {

						aChar = '\t';

					} else if (aChar == 'r') {

						aChar = '\r';

					} else if (aChar == 'n') {

						aChar = '\n';

					} else if (aChar == 'f') {

						aChar = '\f';

					}

					out[outLen++] = aChar;

				}

			} else {

				out[outLen++] = (char) aChar;

			}

		}

		return new String(out, 0, outLen);

	}
	
	/**
	 * md5
	 * @param pwd
	 * @return
	 */
	public  static String MD5(String pwd) {  
        //用于加密的字符  
        char md5String[] = { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9',  
                'a', 'b', 'c', 'd', 'e', 'f' };  
        try {  
            //使用平台的默认字符集将此 String 编码为 byte序列，并将结果存储到一个新的 byte数组中  
            byte[] btInput = pwd.getBytes();  
               
            //信息摘要是安全的单向哈希函数，它接收任意大小的数据，并输出固定长度的哈希值。  
            MessageDigest mdInst = MessageDigest.getInstance("MD5");  
               
            //MessageDigest对象通过使用 update方法处理数据， 使用指定的byte数组更新摘要  
            mdInst.update(btInput);  
               
            // 摘要更新之后，通过调用digest（）执行哈希计算，获得密文  
            byte[] md = mdInst.digest();  
               
            // 把密文转换成十六进制的字符串形式  
            int j = md.length;  
            char str[] = new char[j * 2];  
            int k = 0;  
            for (int i = 0; i < j; i++) {   //  i = 0  
                byte byte0 = md[i];  //95  
                str[k++] = md5String[byte0 >>> 4 & 0xf];    //    5   
                str[k++] = md5String[byte0 & 0xf];   //   F  
            }  
               
            //返回经过加密后的字符串  
            return new String(str);  
               
        } catch (Exception e) {  
            return null;  
        }  
    }  
	
	
	public static String dealShowText(String s){
		
		
		if("".equals(s)||s==null||s.length()==0){
			return "" ;
		}
		
		return s ;
		
	}
	
	
	
	/**
	 * sha1 
	 * @return
	 */
	public static String SHA1(String decript){
		try {
            MessageDigest digest = MessageDigest
                    .getInstance("SHA-1");
            digest.update(decript.getBytes());
            byte messageDigest[] = digest.digest();
            // Create Hex String
            StringBuffer hexString = new StringBuffer();
            // �ֽ�����ת��Ϊ ʮ����� ��
            for (int i = 0; i < messageDigest.length; i++) {
                String shaHex = Integer.toHexString(messageDigest[i] & 0xFF);
                if (shaHex.length() < 2) {
                    hexString.append(0);
                }
                hexString.append(shaHex);
            }
            return hexString.toString();
 
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
        }
        return "";
	}
	
	public static int dip2px(Context context, float dpValue) {  
		  final float scale = context.getResources().getDisplayMetrics().density;  
		  return (int) (dpValue * scale + 0.5f);  
		}  
	
	public static int px2dip(Context context, float pxValue) {  
		  final float scale = context.getResources().getDisplayMetrics().density;  
		  return (int) (pxValue / scale + 0.5f);  
		}   
	
	
	/* public static  void showCustomViewCrouton(Activity context,int parentid,String s) {
		    View view = LayoutInflater.from(context).inflate(R.layout.custom_toast, null);
		    TextView tv = (TextView) view.findViewById(R.id.tv_custom_toast) ;
		    tv.setText(s);
		    final Crouton crouton;
		    crouton = Crouton.make(context, view, parentid);
		    crouton.show();
		  }*/
}
